import file from '@system.file';
import request from '@ohos.request';
import fetch from '@system.fetch';
import router from '@system.router';
import prompt from '@system.prompt';
import geolocation from '@system.geolocation';
import Service from '../../generated/TestService.js';
import dataStorage from '@ohos.data.storage'
import mediaLibrary from '@ohos.multimedia.mediaLibrary';
import featureAbility from '@ohos.ability.featureAbility';
import http from '@ohos.net.http';
import webSocket from '@ohos.net.webSocket';

export default {
    data: {
        sessionid:'',
        sessionname:'五条悟',
        lastmsg:'',
        opheadshot:'',
        headshot:'',
        userid:'',
        opuserid:'',
        messages:[],
        msg:'连接成功',
        ws:null,
        username:'',
    },
    async onInit(){
        var context = featureAbility.getContext()
        var path = await context.getFilesDir()
        let storage = dataStorage.getStorageSync(path + '/mystore')
        this.username = storage.getSync('username', '未登录')
        this.headshot = storage.getSync('headshot', '/common/picture/initheadshot.png')
        this.userid = storage.getSync('userid', '-1')
        if(this.sessionid == ''){
            this.LoadSession()
        }else{
            this.LoadMessage();
            this.LoadWebSocket();
        }
    },
    onDestroy(){
        // 退出界面，主动断开连接
        if (this.ws !== null) {
            this.ws.close((err, value) => {
                if (!err) {
                    console.info("close success");
                } else {
                    console.info("close fail, err is " + JSON.stringify(err));
                }
            });
        }
    },
    LoadSession(){
        var that = this

        let httpRequest= http.createHttp();
        httpRequest.request("http://101.35.82.76:9002/session/CreateOrUpdateSession?"+"userid="+this.userid+"&oppositeid="+this.opuserid,
            {
                method: 'GET',
                readTimeout: 60000,
                connectTimeout: 60000
            },(err, data) => {
                if (!err) {
                    console.info('Result:' + data.result);
                    console.info('code:' + data.responseCode);
                    console.info('header:' + data.header);
                    var res = JSON.stringify(JSON.parse(data.result).data)
                    var sessionid = JSON.stringify(JSON.parse(res).sessionid)
                    that.sessionid = JSON.parse(sessionid)
                    this.LoadMessage();
                    this.LoadWebSocket();
                } else {
                    console.info('error:' + err.data);
                }
            });
    },
    LoadWebSocket(){
        var defaultIpAddress = "ws://101.35.82.76:9003/websocket/imserver/"+this.userid;
        this.ws = webSocket.createWebSocket();
        this.ws.on('open', (err, value) => {
            console.info("on open, status:" + value.status + ", message:" + value.message);
//            var json = {"toUserId":this.opuserid,"contentText":this.msg}
//            // 当收到on('open')事件时，可以通过send()方法与服务器进行通信
//            this.ws.send(json, (err, value) => {
//                if (!err) {
//                    console.info("send success");
//                } else {
//                    console.info("send fail, err:" + JSON.stringify(err));
//                }
//            });
        });
        this.ws.on('message', (err, value) => {
            console.info("on message, message:" + value);
            function Message(id,msg) //声明对象
            {
                this.userid = id;
                this.message= msg;
            }
            this.messages.push(new Message(this.opuserid,value))
        });
        this.ws.on('close', (err, value) => {
            console.info("on close, code is " + value.code + ", reason is " + value.reason);
        });
        this.ws.on('error', (err) => {
            console.info("on error, error:" + JSON.stringify(err));
        });
        this.ws.connect(defaultIpAddress, (err, value) => {
            if (!err) {
                console.info("connect success");
            } else {
                console.info("connect fail, err:" + JSON.stringify(err));
            }
        });
    },
    LoadMessage(){
        var that = this

        let httpRequest= http.createHttp();
        httpRequest.request("http://101.35.82.76:9002/message/getmessaagebysessionid?"+"sessionid="+this.sessionid,
            {
                method: 'GET',
                readTimeout: 60000,
                connectTimeout: 60000
            },(err, data) => {
                if (!err) {
                    console.info('Result:' + data.result);
                    console.info('code:' + data.responseCode);
                    console.info('header:' + data.header);
                    var res = JSON.stringify(JSON.parse(data.result).data)
                    var messages = JSON.stringify(JSON.parse(res).messages)
                    that.messages = JSON.parse(messages)
                } else {
                    console.info('error:' + err.data);
                }
            });
    },
    sendMsg(){
        function Message(id,msg) //声明对象
        {
            this.userid = id;
            this.message= msg;
        }
        this.messages.push(new Message(this.userid,this.msg))

        var json = {"toUserId":this.opuserid,"contentText":this.msg}
        // 当收到on('open')事件时，可以通过send()方法与服务器进行通信
        this.ws.send(json, (err, value) => {
            if (!err) {
                console.info("send success");
            } else {
                console.info("send fail, err:" + JSON.stringify(err));
            }
        });

        var len = this.msg.length
        for(var i = 0; i < len; i++){
            this.$element('input').delete()
        }
    },
    saveMsg(e){
        this.msg = e.value
    },
    TurnBack(){
        router.back();
    },
}
